<template>
  <div class="ssh">
    <div class="mains_contain">
      <div id="xterm" />
    </div>
  </div>
</template>

<script>

import 'xterm/css/xterm.css'
import { Terminal } from 'xterm';
import { FitAddon } from "xterm-addon-fit";
export default {
  data() {
    return {
      term: null,
    }
  },
  mounted() {
    this.initTerm()
    console.log(process.env.BASE_IP);
  },
  beforeDestroy() {
    this.term && this.term.dispose()
  },
  methods: {
    initTerm() {
      const term = new Terminal({
        fontSize: 14,
        cursorBlink: true,
        cursorStyle: "underline",
        scrollback: 100,
      });
      const fitAddon = new FitAddon();
      term.loadAddon(fitAddon);
      term.open(document.getElementById('xterm'));
      fitAddon.fit();
      term.focus();
      this.term = term
      if (term._initialized) {
        return
      }

      term._initialized = true

      term.prompt = () => {
        term.write('\r\n$ ')
      }
      let name = this.$route.query.name
      let times = new Date()
      let nowIp = process.env.BASE_IP
      console.log('times: ', times);
      term.writeln(`开始链接到 ${name}@`)
      term.writeln(`Last Login ${times} from ${nowIp}`)
      term.prompt()
      term.onKey(e => {
        const ev = e.domEvent
        console.log(ev.keyCode, 'ev.keyCode');
        const printable = !ev.altKey && !ev.altGraphKey && !ev.ctrlKey && !ev.metaKey
        if (ev.keyCode === 13) {
          term.prompt()
        } else if (ev.keyCode === 8) {
          if (term._core.buffer.x > 2) {
            term.write('\b \b')
          }
        } else if (printable) {
          term.write(e.key);
        }
      })
    },


  }
}
</script>

<style lang="scss">
.ssh {
  padding: 20px;
  #xterm {
    height: 600px !important;
    .xterm-viewport {
    }
  }
  .terminal {
    padding: 20px !important;
  }
}
</style>